package cn.psvmc.cxzapi.util;

import cn.psvmc.cxzapi.config.ConfigKey;
import cn.psvmc.cxzapi.exception.ServiceException;
import cn.psvmc.cxzapi.model.order.TOrder;
import cn.psvmc.cxzapi.model.order.TOrderBill;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @Author YWX
 * @Classname FileUtils
 * @Description 文件处理工具类
 * @Date 2024/9/7 9:50
 **/
@Slf4j
public class FileUtils {

    /**
     * @Description 读取文件内容
     * @Date 2024/9/7 9:29
     * @Author YWX
     * @Param [filePath]
     * @Return java.util.List<java.lang.String>
     **/
    public static List<String> readFileByLines(String filePath) {
        List<String> lines = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                lines.add(line);
            }
        } catch (IOException e) {
            FileUtils.log.error("读取文件失败:{}", e.getMessage());
            throw new ServiceException("读取文件失败!");
        }
        return lines;
    }

    /**
     * @Description 生成个人信息授权书html文件
     * @Date 2024/9/7 9:33
     * @Author YWX
     * @Param [name]
     * @Return void
     **/
    public static String generateHtml(String name) {
        String filePath = ConfigKey.pdfpath + "pemplate/auth_people.txt";
        String htmlPath = ConfigKey.pdfpath + OssService.generateRandomAlphanumeric(4) + ".html";
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(htmlPath))) {
            List<String> lines = FileUtils.readFileByLines(filePath);
            int num = 1;
            for (String line : lines) {
                if (num == 31) {
                    line = line.replace("{{authPeople}}", name);
                } else if (num == 32) {
                    line = line.replace("{{authDate}}", ToolUtils.getNowDateFormat("yyyy年 MM月 dd日"));
                }
                bw.write(line);
                bw.newLine();
                num++;
            }
            return htmlPath;
        } catch (IOException e) {
            FileUtils.log.error("生成html失败:{}", e.getMessage());
            throw new ServiceException("生成html失败!");
        }
    }

    /**
     * @Description 生成租赁服务协议html文件
     * @Date 2024/10/4 21:56
     * @Author YWX
     * @Param [order, map]
     * @Return java.lang.String
     **/
    public static String generateLeaseContractHtml(TOrder order, List<TOrderBill> bills, Map<String, String> map) {
        String filePath = ConfigKey.pdfpath + "pemplate/lease_contract.txt";
        String htmlPath = ConfigKey.pdfpath + CodeUtil.generateOrderCode() + ".html";
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(htmlPath))) {
            List<String> lines = FileUtils.readFileByLines(filePath);
            String orderCode = order.getOrderCode();
            String username = order.getUsername();
            String realName = map.get("realName");
            String userphone = order.getUserphone();
            String userAddress = order.getUserAddress();
            String legalPersonName = map.get("legalPersonName");
            String storeaddress = map.get("storeaddress");
            String storename = map.get("storename");
            String businessName = map.get("businessName");
            String idNumber = map.get("idNumber");
            String goodsName = map.get("goodsName");
            String gsName = map.get("gsName");
            String jfQsq = map.get("storeSeal");
            String yfQsq = map.get("customerseal");

            String authDate = ToolUtils.getNowDateFormat("yyyy年 MM月 dd日");
            Double rentAfterCoupon = order.getRentAfterCoupon();
            String rent = ToolUtils.objToString(rentAfterCoupon);
            LocalDateTime planBegin = order.getPlanBegin();
            String year1 = ToolUtils.objToString(planBegin.getYear());
            String month1 = ToolUtils.objToString(planBegin.getMonthValue());
            String day1 = ToolUtils.objToString(planBegin.getDayOfMonth());
            LocalDateTime planEnd = order.getPlanEnd();
            String year2 = ToolUtils.objToString(planEnd.getYear());
            String month2 = ToolUtils.objToString(planEnd.getMonthValue());
            String day2 = ToolUtils.objToString(planEnd.getDayOfMonth());
            String orderDay = ToolUtils.objToString(order.getDay());
            Double onePrice = ToolUtils.divideAndCeil(rentAfterCoupon, order.getNum());//单件租赁物费用
            Double shippingFee = order.getShippingFee();//运费
            Double oneTotalPrice = ToolUtils.add(onePrice, shippingFee);//单件租赁物租赁费用总额
            Double totalPrice = ToolUtils.add(rentAfterCoupon, shippingFee);//所有租赁物租赁服务期内租赁费用总额
            Double buyPriceAfterStore = order.getBuyPriceAfterStore();
            Double qyj = ToolUtils.divideAndCeil(order.getBuyPrice(), order.getNum());//单件商品签约价
            //单件租赁物的留购价款=签约价-单件租赁物租赁费用总额
            String oneBuyPrice;
            if (qyj.compareTo(oneTotalPrice) <= 0) {
                oneBuyPrice = "0.00";
            } else {
                oneBuyPrice = ToolUtils.objToString(ToolUtils.subtract(qyj, oneTotalPrice));
            }
            //所有租赁物的留购价款
            String buyPrice;
            if (order.getBuyPrice().compareTo(totalPrice) <= 0) {
                buyPrice = "0.00";
            } else {
                buyPrice = ToolUtils.objToString(ToolUtils.subtract(order.getBuyPrice(), totalPrice));
            }
            StringBuffer billTr = new StringBuffer();
            Double orderBuyPrice = order.getBuyPrice();
            double storeAmount = 0.0;
            for (TOrderBill bill : bills) {
                billTr.append("<tr>");
                billTr.append("<td>第").append(bill.getPeriod()).append("期</td>");
                billTr.append("<td>￥").append(bill.getPayAmount()).append("</td>");
                billTr.append("<td>").append(bill.getPlanDate()).append("</td>");
                billTr.append("<td>￥").append(ToolUtils.subtract(orderBuyPrice, storeAmount)).append("</td>");
                billTr.append("</tr>");
                storeAmount = ToolUtils.add(storeAmount, bill.getStoreAmount());
            }
            for (String line : lines) {
                line = line.replace("{{orderCode}}", orderCode);

                line = line.replace("{{legalPersonName}}", legalPersonName);
                line = line.replace("{{storeaddress}}", storeaddress);
                line = line.replace("{{storename}}", storename);
                line = line.replace("{{bills}}", billTr.toString());

                line = line.replace("{{username}}", username);
                line = line.replace("{{realName}}", realName);
                line = line.replace("{{idNumber}}", idNumber);
                line = line.replace("{{userAddress}}", userAddress);
                line = line.replace("{{userphone}}", userphone);

                line = line.replace("{{goodsName}}", goodsName);
                line = line.replace("{{gsName}}", gsName);
                line = line.replace("{{rent}}", ToolUtils.objToString(qyj));
                line = line.replace("{{year1}}", year1);
                line = line.replace("{{month1}}", month1);
                line = line.replace("{{day1}}", day1);
                line = line.replace("{{year2}}", year2);
                line = line.replace("{{month2}}", month2);
                line = line.replace("{{day2}}", day2);
                line = line.replace("{{orderDay}}", orderDay);
                line = line.replace("{{onePrice}}", ToolUtils.objToString(onePrice));
                line = line.replace("{{totalPrice}}", ToolUtils.objToString(totalPrice));
                line = line.replace("{{oneBuyPrice}}", oneBuyPrice);
                line = line.replace("{{buyPrice}}", buyPrice);
                line = line.replace("{{authDate}}", authDate);
                line = line.replace("{{jfQsq}}", jfQsq);
                line = line.replace("{{yfQsq}}", yfQsq);
                line = line.replace("{{businessName}}", businessName);
                bw.write(line);
                bw.newLine();
            }
            return htmlPath;
        } catch (IOException e) {
            FileUtils.log.error("生成租赁服务协议html失败:{}", e.getMessage());
            throw new ServiceException("生成租赁服务协议html失败!");
        }
    }

    /**
     * @Description 生成定制租赁补充协议html文件
     * @Date 2024/10/4 22:14
     * @Author YWX
     * @Param [order, map]
     * @Return java.lang.String
     **/
    public static String generateRenewContractHtml(TOrder order, Map<String, String> map) {
        String filePath = ConfigKey.pdfpath + "pemplate/renew_contract.txt";
        String htmlPath = ConfigKey.pdfpath + CodeUtil.generateOrderCode() + ".html";
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(htmlPath))) {
            List<String> lines = FileUtils.readFileByLines(filePath);
            String orderCode = order.getOrderCode();
            Double rentAfterCoupon = order.getRentAfterCoupon();
            String breachFee = ToolUtils.objToString(ToolUtils.multiply(rentAfterCoupon, 0.2));
            String username = order.getUsername();
            String legalPersonName = map.get("legalPersonName");
            LocalDateTime now = LocalDateTime.now();
            String year = ToolUtils.objToString(now.getYear());
            String month = ToolUtils.objToString(now.getMonthValue());
            String day = ToolUtils.objToString(now.getDayOfMonth());
            for (String line : lines) {
                line = line.replace("{{orderCode}}", orderCode);
                line = line.replace("{{legalPersonName}}", legalPersonName);
                line = line.replace("{{username}}", username);
                line = line.replace("{{year}}", year);
                line = line.replace("{{month}}", month);
                line = line.replace("{{day}}", day);
                line = line.replace("{{breachFee}}", breachFee);
                line = line.replace("{{authDate}}", ToolUtils.getNowDateFormat("yyyy年 MM月 dd日"));
                bw.write(line);
                bw.newLine();
            }
            return htmlPath;
        } catch (IOException e) {
            FileUtils.log.error("生成定制租赁补充协议html失败:{}", e.getMessage());
            throw new ServiceException("生成定制租赁补充协议html失败!");
        }
    }

    /**
     * @Description 删除本地文件
     * @Date 2024/9/7 10:00
     * @Author YWX
     * @Param [filePath]
     * @Return void
     **/
    public static void deleteFile(String filePath) {
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        }
    }
}

